package common

import (
	"crypto/sha1"
	"encoding/hex"
	"gitee.com/zhengjianfeng/pay/conf"
	"gitee.com/zhengjianfeng/pay/web/middleware/jwts"
	"github.com/iris-contrib/middleware/jwt"
	"github.com/kataras/iris/v12"
	"time"
)

// 所有接口统一响应结果
type ResponseData struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// 返回登录凭证
type AccountReturnData struct {
	Token string `json:"token"`
}

// 获取账号登录密码加密结果
func EncryptionForAccount(pwd string, username string) string {
	var (
		sum [20]byte
	)
	sum = sha1.Sum([]byte(pwd + username))
	return hex.EncodeToString(sum[:])
}

// 获取登录成功后需要保存的信息
func GetLoginInfo(loginInfo *jwts.LoginInfo) jwt.MapClaims {
	return jwt.MapClaims{
		"account_id":  loginInfo.AccountId,
		"nickname":    loginInfo.Nickname,
		"username":    loginInfo.Username,
		"role_type":   loginInfo.RoleType,
		"relevant_id": loginInfo.RelevantId,
		"exp":         loginInfo.Exp,
	}
}

// 响应结果
func GetResponseData(code int, msg string, data interface{}) ResponseData {
	return ResponseData{
		Code: code,
		Msg:  msg,
		Data: data,
	}
}

// 获取请求参数
func GetRequestParams(ctx iris.Context, data interface{}) (err error) {
	if err = ctx.ReadJSON(data); err != nil {
		return err
	}
	return nil
}

// 获取登录令牌
func GetAuthToken(userInfo *jwts.LoginInfo) (tokenString string) {
	// jwt 获取token
	userInfo.Exp = time.Now().Add(2 * time.Hour * time.Duration(1)).Unix()
	
	claims := GetLoginInfo(userInfo)

	token := jwt.NewTokenWithClaims(jwt.SigningMethodHS256, claims)

	tokenString, _ = token.SignedString(conf.JwtSecret)

	return conf.JwtTokenHead + tokenString
}

// 检查是否是管理员
func CheckIsAdmin(roleType int) bool {
	if roleType == PAY_ROLE_TYPE_ADMIN {
		return true
	}
	return false
}
